/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.view.saving;

import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.event.CloseEvent;
import src.domain.customer.Customer;
import src.domain.gl.Tax;
import src.domain.saving.Saving;
import src.domain.saving.Savjoint;
import src.domain.saving.Savprod;
import src.domain.saving.Savpurpose;
import src.domain.security.Users;
import src.services.CRUEDService;
import src.services.customer.CustomerModel;
import src.services.gl.TaxModel;
import src.services.saving.SavingModel;
import src.services.saving.SavprodConverter;
import src.services.saving.SavprodModel;
import src.services.saving.SavpurposeModel;
import src.util.Constanta;
import src.util.Messager;
import src.view.security.LoginBean;

/**
 *
 * @author jay
 */
@ManagedBean
@SessionScoped
public class SavingBean implements Serializable {

    private List<Savprod> avaibleProduct;
    private List<Savpurpose> avaiblePurpose;
    private Saving saving;
    private Savjoint unsaveJoint;
    private CRUEDService csHelper;
    private SavprodModel prodHelper;
    private SavpurposeModel purHelper;
    private SavingModel helper;
    private Integer branchId, joinIdx, searchSatus=1; //1: saerch customer; 2: search join
    private boolean editMode = false, authorized=false, insertionMode=false, editDetailMode=true;
    private String defaultButton="doNothingSaving";
    private boolean showLookup=false;
    private Users users;
    
    public SavingBean() {
        super();
        ambilUser();
        this.csHelper     = new CRUEDService();
        this.prodHelper   = new SavprodModel();
        this.purHelper    = new SavpurposeModel();
        this.helper       = new SavingModel();        
        
        newData();
        editMode = false;
    }
    
     private boolean cekConfig() {
        boolean complete=true;
        this.branchId = users.getBranch().getBranchId();
        
        if (this.branchId==null) complete=false;
        if(complete==false) Messager.showWarning("savingUnconfig");
        return complete;
    }

    public boolean isShowLookup() {
        return showLookup;
    }

    public void setShowLookup(boolean showLookup) {
        this.showLookup = showLookup;
    }
         
    public boolean isEditMode() {
        return editMode;
    }

    public Integer getSearchSatus() {
        return searchSatus;
    }

    public void setSearchSatus(Integer searchSatus) {
        this.searchSatus = searchSatus;
    }
        
    public boolean isAuthorized() {
        return authorized;
    }

    public Savjoint getUnsaveJoint() {
        return unsaveJoint;
    }

    public void setUnsaveJoint(Savjoint unsaveJoint) {
        this.unsaveJoint = unsaveJoint;
    }
    
    public Saving getSaving() {
        return saving;
    }

    public void setSaving(Saving saving) {
        this.saving = saving;
    }

    public List<Savprod> getAvaibleProduct() {
        return avaibleProduct;
    }

    public void setAvaibleProduct(List<Savprod> avaibleProduct) {
        this.avaibleProduct = avaibleProduct;
    }
    
    public List<Savpurpose> getAvaiblePurpose() {
        return avaiblePurpose; 
    }
    
    public void handleNumberChange() {
        boolean eksis = helper.isSavingExist(saving.getAccountNo(), saving.getSavaccntId());
        if (eksis) {
            Messager.showWarning("savingNoIsExist");
            saving.setAccountNo(Constanta.AUTO_NUMBERING);
        } 
    }
    
    private void newNumber() {
        
        //if ((saving.getBranchId() != null) && (saving.getSavprod().getSavproductId() !=null)) {
        //    Numbering currentNo = csHelper.getNextTrxNumber(1, saving.getBranchId(), saving.getSavprod().getSavproductId(), 1);
        //    saving.setAccountNo(currentNo.getTrxNum());
        //}
    }
        
    private void initForm() {
        cekConfig();
        this.avaibleProduct = SavprodConverter.products;//prodHelper.findAll(null);
        this.avaiblePurpose = purHelper.findAll(null);
        defaultButton="doNothingSaving";
        showLookup=false;
        this.editMode = true;
        this.authorized = true;
    }
    
    public final void newData() { 
        initForm();
        
        if (this.saving!=null) saving = null;
        this.saving = new Saving(true);
        this.saving.getSavjoints().add(new Savjoint());        
        this.saving.setBranchId(branchId);
        insertionMode = true;
    }
    
    public void openData() {
        initForm();
        insertionMode = false;
    }
    
    private void removeEmptyJoin(){
        for(int i = 0; i< saving.getSavjoints().size(); i++){
           if(saving.getSavjoints().get(i).getCustomer().getCustomerId()==null) {
               saving.getSavjoints().remove(i);
               i--;
           }
        }
    }
    
    public void newJoint() {
        this.unsaveJoint = new Savjoint();
        editDetailMode = false;
    }
    
    public void editJoint(Savjoint join) {
        this.unsaveJoint = Savjoint.clone(join);
        joinIdx = saving.getSavjoints().indexOf(join);
        editDetailMode = true;
    }
    
    public void saveJoint() {
        boolean success=true;
        
        try {
            
            if(!editDetailMode) {
                this.saving.getSavjoints().add(unsaveJoint);
                removeEmptyJoin();
                
            } else this.saving.getSavjoints().set(joinIdx, Savjoint.clone(unsaveJoint));

        } catch (RuntimeException e) {success=false;
        } finally {Messager.showSaveUpdateStatus(success);}
        
        /*
        try {
            Integer custId1 = unsaveJoint.getCustomer().getCustomerId();
            Integer custId0 = saving.getCustomer().getCustomerId();
            
            if (unsaveJoint!=null) {
                this.unsaveJoint.setCustomer(unsaveJoint.getCustomer());
                
                if (custId0==null) custId0 = 0;
                if (custId1==null) custId0 = 0;

                if(custId0.compareTo(custId1) == 0) {
                    Messager.showInfo("Anggota sama.");

                } else {

                    boolean found=false;
                    int idx=0;

                    while (idx < saving.getSavjoints().size() && !found) {
                        Savjoint sav = saving.getSavjoints().get(idx);
                        if(sav.getCustomer().getCustomerId() != null)
                            found = custId1.equals(sav.getCustomer().getCustomerId()) ? true:false;
                        else found = false;
                        idx++;
                    }
                    if(!found) saving.getSavjoints().add(joint);
                }
                removeEmptyJoin();
            }
        } catch (RuntimeException e) {success=false;
        } finally {Messager.showSaveUpdateStatus(success);}
        * 
        */
    }
    
    public Customer getCustomerByCIF(String cif) {
        CustomerModel custhelper = new CustomerModel();
        Customer cust = custhelper.getByCif(cif);
        return cust;
    }
    
    public void getSavingCustomer(String cif) {
        if ("null".equals(cif)) cif = saving.getCustomer().getCif();
                
        if (cif!=null ) {
            Customer customer = getCustomerByCIF(cif);
            if (customer==null) {
                //reset
                this.saving.setCustomer(new Customer());
                Messager.showWarning("customerNotFound");
            }
            else {
                this.saving.setCustomer(customer);
                //this.defaultButton= "submitSaving";
                this.defaultButton= "doNothingSaving";
                
                if (saving.getSavprod().getSavproductId() != null) {
                    boolean validprod = prodHelper.validateProdcut(
                        saving.getCustomer().getCustomerId(), saving.getSavprod().getSavproductId());
                
                    if (!validprod) Messager.showWarning("savprodcompulRequired");
                }
            }
        }
    }
    
    public void getJointCustomer(String cif) {
        if ("null".equals(cif)) cif = unsaveJoint.getCustomer().getCif();
                
        if (cif!=null ) {
            Customer customer = getCustomerByCIF(cif);
            if (customer==null) {
                //reset
                this.unsaveJoint.setCustomer(new Customer());
                Messager.showWarning("customerNotFound");
            }
            else this.unsaveJoint.setCustomer(customer);
        }
    }
    
    public void handleProdChange() {  
//        Savprod produk= new Savprod();
  //      Integer id = this.saving.getSavprod().getSavproductId();
        if (this.saving.getSavprod() != null) {
            //produk = prodHelper.getById(id);
            
            if (saving.getCustomer().getCustomerId() != null) {
                
                boolean validprod = prodHelper.validateProdcut(
                        saving.getCustomer().getCustomerId(), saving.getSavprod().getSavproductId());
                
                if (!validprod) Messager.showWarning("savprodcompulRequired");
            }
        }
        
        //this.saving.setSavprod(produk);
        newNumber();
    }  
    
    public void handleRemoveRow() {  
        if (saving.getSavjoints().size() == 1) saving.getSavjoints().add(new Savjoint());
    }  
    
    public Double getInterestTaxName(Integer id) {  
        TaxModel tm = new TaxModel();
        Double txRate = null;
        Tax tax = tm.getById(id);
        
        if (tax != null) txRate = tax.getTaxRate().doubleValue();
        return txRate;
    }
            
    public boolean validate() {
        boolean validprod = prodHelper.validateProdcut(
            saving.getCustomer().getCustomerId(), saving.getSavprod().getSavproductId());
               
        if (!validprod) Messager.showWarning("savprodcompulRequired");
        else validprod = cekConfig();                
        
        if (validprod) {
            //productExist = helper.isProductExist(unsaveData.getProductNo(), unsaveData.getSavproductId());
            //if (productExist==true) {
              //  Messager.showError("codeIsExist");
                
            // }
        }
        return validprod;
    }
    
    private void save() {
        Integer authorizedId = helper.authorized(saving.getSavaccntId());
        this.authorized = (authorizedId != null ? true : false);
        saving.setApprovalUid(authorizedId);
                        
        //pastikan yg customernya ga diisi dibuang
        if (this.saving.getJoinAccnt()) removeEmptyJoin();
        
        //jika tipenya bukan join, delete
        else saving.getSavjoints().clear();
                        
        this.saving.setSavjoints(saving.getSavjoints());
        boolean success = helper.saveData(this.saving);
        //this.editMode = (!success || !authorized);
        this.editMode = (!success);
        
        //init savjointId -->> dibutuhkan oleh selectable datatable
        if (saving.getSavjoints().isEmpty()) saving.getSavjoints().add(new Savjoint());
                
        //if (!success) 
        Messager.showSaveUpdateStatus(success);
        
        if (!authorized && success) Messager.showWarning("unauthorized"); 
        
        //inputan editable
        if (!success) authorized = true;
        
        //kalo sukses & athorized....
        else {
            if (authorized) authorized = false;
        }    
        
        // re-insert
        if (!success && insertionMode) saving.setSavaccntId(null);
        else insertionMode = false;
        
        RequestContext.getCurrentInstance().addCallbackParam("success", success); 
    }
      
    public void trySave() {
        if (validate()) save();
    }

    public String getDefaultButton() {
        return defaultButton;
    }

    public void setDefaultButton(String defaultButton) {
        this.defaultButton = defaultButton;
    }
    
    public void handleCloseLookup(CloseEvent event) {
        this.showLookup=false;
    }
    
    private void ambilUser() {
        FacesContext context = FacesContext.getCurrentInstance();
        LoginBean logBean = (LoginBean) context.getApplication().evaluateExpressionGet(context, "#{loginBean}", LoginBean.class);
        this.users = logBean.getSelectedUser();
    }
           
}
